package servlets;

import java.io.IOException;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ServletsUtil {

	private static final String START_FROM = "startFrom";
	private static final String PAGE_NUMBER = "pageNumber";
	public static final String RESULT = "result";

	/**
	 * 
	 * @param request
	 * @param response
	 * @return the timestamp from the request (null if the parameter is invalid)
	 * @throws IOException
	 */
	public static Timestamp getStartFrom(HttpServletRequest request, HttpServletResponse response) throws IOException{
		 long millis = castRequestParameter(START_FROM,request,response);
		 return (millis != -1) ? new Timestamp(millis) : null;
	}

	public static int getPageNumber(HttpServletRequest request, HttpServletResponse response) throws IOException{
		return (int)castRequestParameter(PAGE_NUMBER,request,response);
	}
/**
 * return the userID form the session
 * @param request
 * @return
 */
	public static long getUserID(HttpServletRequest request){
			HttpSession session = request.getSession();
			Object userIDObject = session.getAttribute(LoginServlet.LOGGED_USER_ID);
			try{
			return userIDObject != null ? (long)userIDObject : -1;
			}catch(NumberFormatException e){
				e.printStackTrace();
				return -1;
			}

	}
	/**
	 * gets the get method number parameters 
	 * @param param
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public static long castRequestParameter(String param,HttpServletRequest request, HttpServletResponse response) throws IOException{
		String numberAsString = request.getParameter(param);
		long result = -1;
		try{
			if(numberAsString != null)
				result = Long.parseLong(numberAsString);
		}catch(NumberFormatException e){
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		}
		return result;
	}

	
}
